<template>
  <view class="work-mode-container">
    <view class="header">
      <view class="title">工作模式</view>
      <view class="subtitle">您的位置将每30秒自动更新一次</view>
    </view>
    
    <view class="map-container">
      <map :longitude="longitude" :latitude="latitude" :markers="markers" :circles="circles"
        style="width: 100%; height: 100%;" :scale="18">
      </map>
    </view>
    
    <view class="status-card">
      <view class="status-header">
        <text class="status-title">工作状态</text>
        <text class="status-time">已工作: {{ formatWorkTime() }}</text>
      </view>
      <view class="status-content">
        <view class="status-item">
          <text class="item-label">当前位置</text>
          <text class="item-value">{{ currentAddress || '获取中...' }}</text>
        </view>
        <view class="status-item">
          <text class="item-label">距离签到点</text>
          <text class="item-value">{{ calculateDistance() }}米</text>
        </view>
        <view class="status-item">
          <text class="item-label">最近更新</text>
          <text class="item-value">{{ lastUpdateTime || '尚未更新' }}</text>
        </view>
      </view>
    </view>
    
    <view class="log-panel">
      <view class="log-header">
        <text class="log-title">位置更新日志</text>
        <text class="log-count">共 {{ locationLogs.length }} 条</text>
      </view>
      <scroll-view scroll-y class="log-content" :scroll-top="scrollTop">
        <view v-for="(log, index) in locationLogs" :key="index" class="log-item">
          <text class="log-time">{{ log.time }}</text>
          <text class="log-message" :class="{'log-success': log.success, 'log-error': !log.success}">
            {{ log.message }}
          </text>
        </view>
      </scroll-view>
    </view>
    
    <view class="action-bar">
      <button class="btn btn-primary" @click="updateLocation">立即更新位置</button>
      <button class="btn btn-danger" @click="stopWork">结束工作</button>
    </view>
  </view>
</template>

<script>
import request from '@/utils/request.js';
export default {
  data() {
    return {
      lessonId: null,
      latitude: 0, // 当前位置纬度
      longitude: 0, // 当前位置经度
      markers: [], // 位置标记
      circles: [], // 范围圈
      checkInLocation: { // 签到点经纬度
        longitude: 0,
        latitude: 0
      },
      currentAddress: '', // 当前地址
      startTime: null, // 开始工作时间
      lastUpdateTime: '', // 最后更新时间
      locationLogs: [], // 位置更新日志
      locationTimer: null, // 定时器
      scrollTop: 0, // 日志滚动位置
      updateInterval: 30000, // 更新间隔，30秒
    }
  },
  onLoad(option) {
    console.log('工作模式页面参数:', option);
    this.lessonId = option.lessonId - 0;
    
    // 获取签到点信息
    this.getLessonDetail();
    
    // 初始化开始时间
    this.startTime = new Date();
    
    // 获取当前位置
    this.getLocation();
    
    // 启动定时更新
    this.startLocationUpdates();
  },
  onUnload() {
    // 页面卸载时清除定时器
    this.stopLocationUpdates();
  },
  methods: {
    getLessonDetail() {
      request.post(`/lesson/detail?lessonId=${this.lessonId}`)
        .then(res => {
          let lesson = res.data;
          this.checkInLocation.longitude = lesson.signLocationLong;
          this.checkInLocation.latitude = lesson.signLocationLat;
          console.log('签到点位置:', this.checkInLocation);
          
          // 初始化地图标记
          this.initMarkers();
        })
        .catch(err => {
          console.error('获取课程详情失败:', err);
          this.addLog(false, '获取课程信息失败');
          uni.showToast({
            title: '获取课程信息失败',
            icon: 'none'
          });
        });
    },
    getLocation() {
      uni.getLocation({
        type: 'gcj02',
        success: (res) => {
          console.log('获取当前位置成功:', res);
          const { latitude, longitude } = res;
          this.latitude = latitude;
          this.longitude = longitude;
          
          // 更新地图标记
          this.initMarkers();
          
          // 获取地址信息
          this.getAddressInfo(latitude, longitude);
        },
        fail: (err) => {
          console.error('获取位置失败:', err);
          this.addLog(false, '获取位置失败，请检查定位权限');
          uni.showToast({
            title: '获取位置失败',
            icon: 'none'
          });
        }
      });
    },
    getAddressInfo(latitude, longitude) {
      this.currentAddress = `${latitude.toFixed(6)}, ${longitude.toFixed(6)}`;
      this.addLog(true, '位置已更新');
    },
    initMarkers() {
      this.markers = [];
      this.circles = [];
      
      // 添加当前位置标记
      if (this.latitude && this.longitude) {
        this.markers.push({
          id: 1,
          latitude: this.latitude,
          longitude: this.longitude,
          iconPath: '../../static/imges/location-user.png',
          width: 40,
          height: 40
        });
      }
      
      // 添加签到点标记
      if (this.checkInLocation.latitude && this.checkInLocation.longitude) {
        this.markers.push({
          id: 2,
          latitude: this.checkInLocation.latitude,
          longitude: this.checkInLocation.longitude,
          iconPath: '../../static/imges/location-target.png',
          width: 40,
          height: 40
        });
        
        // 添加签到范围圈
        this.circles.push({
          latitude: this.checkInLocation.latitude,
          longitude: this.checkInLocation.longitude,
          color: '#1890FF10',
          fillColor: '#1890FF20',
          radius: 100,
          strokeWidth: 2
        });
      }
    },
    calculateDistance() {
      if (!this.checkInLocation.latitude || !this.checkInLocation.longitude) {
        return '未知';
      }
      
      const distance = this.getDistance(
        this.latitude,
        this.longitude,
        this.checkInLocation.latitude,
        this.checkInLocation.longitude
      );
      
      return Math.round(distance);
    },
    getDistance(lat1, lon1, lat2, lon2) {
      const R = 6371000; // 地球半径，单位米
      const dLat = this.deg2rad(lat2 - lat1);
      const dLon = this.deg2rad(lon2 - lon1);
      const a = 
        Math.sin(dLat/2) * Math.sin(dLat/2) +
        Math.cos(this.deg2rad(lat1)) * Math.cos(this.deg2rad(lat2)) * 
        Math.sin(dLon/2) * Math.sin(dLon/2); 
      const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
      const d = R * c;
      return d;
    },
    deg2rad(deg) {
      return deg * (Math.PI/180);
    },
    formatWorkTime() {
      if (!this.startTime) return '00:00:00';
      
      const now = new Date();
      const diff = Math.floor((now - this.startTime) / 1000);
      
      const hours = Math.floor(diff / 3600).toString().padStart(2, '0');
      const minutes = Math.floor((diff % 3600) / 60).toString().padStart(2, '0');
      const seconds = Math.floor(diff % 60).toString().padStart(2, '0');
      
      return `${hours}:${minutes}:${seconds}`;
    },
    startLocationUpdates() {
      // 先清除可能存在的定时器
      this.stopLocationUpdates();
      
      // 添加开始工作日志
      this.addLog(true, '开始工作模式，位置监控已启动');
      
      // 设置定时器，每30秒更新一次位置
      this.locationTimer = setInterval(() => {
        this.updateLocation();
      }, this.updateInterval);
    },
    stopLocationUpdates() {
      if (this.locationTimer) {
        clearInterval(this.locationTimer);
        this.locationTimer = null;
      }
    },
    updateLocation() {
      this.getLocation();
      
      // 发送位置到服务器
      this.sendLocationToServer();
    },
    sendLocationToServer() {
      const params = {
        lessonId: this.lessonId,
        latitude: this.latitude,
        longitude: this.longitude
      };
      
      request.post('/location/update', params)
        .then(res => {
          console.log('位置更新成功:', res);
          this.addLog(true, '位置已成功发送到服务器');
        })
        .catch(err => {
          console.error('位置更新失败:', err);
          this.addLog(false, '位置发送失败，请检查网络');
        });
    },
    addLog(success, message) {
      const now = new Date();
      const timeStr = `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}:${now.getSeconds().toString().padStart(2, '0')}`;
      
      this.locationLogs.unshift({
        time: timeStr,
        message: message,
        success: success
      });
      
      // 限制日志数量
      if (this.locationLogs.length > 50) {
        this.locationLogs = this.locationLogs.slice(0, 50);
      }
      
      // 更新最后更新时间
      if (success) {
        this.lastUpdateTime = timeStr;
      }
      
      // 滚动到顶部
      this.$nextTick(() => {
        this.scrollTop = 0;
      });
    },
    stopWork() {
      uni.showModal({
        title: '结束工作',
        content: '确定要结束当前工作吗？',
        success: (res) => {
          if (res.confirm) {
            // 停止位置更新
            this.stopLocationUpdates();
            
            // 添加结束工作日志
            this.addLog(true, '工作已结束，位置监控已停止');
            
            // 返回上一页
            setTimeout(() => {
              uni.navigateBack();
            }, 1000);
          }
        }
      });
    }
  }
}
</script>

<style>
.work-mode-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f7fa;
}

.header {
  background: linear-gradient(to right, #1890ff, #36a6ff);
  padding: 30rpx 40rpx;
  color: #fff;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  margin-bottom: 10rpx;
}

.subtitle {
  font-size: 24rpx;
  opacity: 0.8;
}

.map-container {
  height: 400rpx;
  margin: 20rpx;
  border-radius: 12rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
}

.status-card {
  margin: 0 20rpx 20rpx;
  background-color: #fff;
  border-radius: 12rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.status-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx;
  border-bottom: 1px solid #f0f0f0;
}

.status-title {
  font-size: 28rpx;
  font-weight: 500;
  color: #333;
}

.status-time {
  font-size: 24rpx;
  color: #1890ff;
  font-weight: 500;
}

.status-content {
  padding: 10rpx 0;
}

.status-item {
  display: flex;
  justify-content: space-between;
  padding: 16rpx 20rpx;
  border-bottom: 1px solid #f9f9f9;
}

.status-item:last-child {
  border-bottom: none;
}

.item-label {
  font-size: 26rpx;
  color: #666;
}

.item-value {
  font-size: 26rpx;
  color: #333;
  font-weight: 500;
  max-width: 70%;
  text-align: right;
}

.log-panel {
  flex: 1;
  margin: 0 20rpx 20rpx;
  background-color: #fff;
  border-radius: 12rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  display: flex;
  flex-direction: column;
  min-height: 200rpx;
}

.log-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx;
  border-bottom: 1px solid #f0f0f0;
}

.log-title {
  font-size: 28rpx;
  font-weight: 500;
  color: #333;
}

.log-count {
  font-size: 24rpx;
  color: #999;
}

.log-content {
  flex: 1;
  padding: 10rpx 20rpx;
}

.log-item {
  display: flex;
  padding: 12rpx 0;
  font-size: 24rpx;
  border-bottom: 1px solid #f9f9f9;
}

.log-time {
  color: #999;
  margin-right: 10rpx;
  flex-shrink: 0;
}

.log-message {
  flex: 1;
}

.log-success {
  color: #52c41a;
}

.log-error {
  color: #f5222d;
}

.action-bar {
  display: flex;
  justify-content: space-between;
  padding: 20rpx;
  background-color: #fff;
  box-shadow: 0 -2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.btn {
  flex: 1;
  height: 80rpx;
  line-height: 80rpx;
  text-align: center;
  color: #fff;
  border-radius: 40rpx;
  font-size: 28rpx;
  font-weight: 500;
  margin: 0 10rpx;
}

.btn-primary {
  background: linear-gradient(to right, #1890ff, #36a6ff);
}

.btn-danger {
  background: linear-gradient(to right, #ff4d4f, #ff7875);
}
</style> 